package com.slkj.shilixiaoyuanapp.ui.teacher.tool.repair;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.code.ToolCode;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.entity.commitdata.RepairCommitData;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.common.CommonToolHistoryActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.leave.AplyyLeaveActivity;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_aplyy_repair, title = "报修", rightHint = "历史记录")
public class AplyyRepairActivity extends BaseActivity {
    @BindView(R.id.recyc_pic)
    RecyclerView recycerPic;
    @BindView(R.id.tv_spr)
    TextView tvSpr;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_now_day_time)
    TextView tvNowDayTime;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    ArrayList<String> picPaths = new ArrayList<>();
    ChosePicAdapter adapter;
    public TakePictureUtils takePictureUtils;
    List<Integer> sqrIds = new ArrayList<>();
    private ArrayList<PeopleEntity> peopleEntities = new ArrayList<>();
    public static final String tag = "AplyyRepairActivity";

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        recycerPic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new ChosePicAdapter(picPaths,this);
        recycerPic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }
            @Override public void failed(int errorCode, List<String> deniedPermissions) { }
        });
        tvUserName.setText(UserRequest.getInstance().getUser().getUser().getUName());
        tvNowDayTime.setText(TimeUtils.getNowNyr());

    }
    @OnClick(R.id.tv_up)
    void upData() {
        String name  =  editName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            showToast("请输入报修设备名称");
            return;
        }
        String context = editContent.getText();
        if (TextUtils.isEmpty(context)) {
            showToast("请输入损坏情况");
            return;
        }
        if (sqrIds.size() == 0) {
            showToast("请选择审批人");
            return;
        }
        UpdataFileUtil.UpImgObservable("auditRepair", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        RepairCommitData commitData = new RepairCommitData(name,context,result);
                        List<RepairCommitData> dataList = new ArrayList<>();
                        dataList.add(commitData);
                        Gson gson = new Gson();
                        String jsonData =  gson.toJson(dataList);
                        return HttpHeper.get().toolService().addBx(jsonData, sqrIds.toString());
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(AplyyRepairActivity.this,data);
                        clearContent();
                    }
                });

    }

    @Override
    protected void onRightTitleClick() {
        CommonToolHistoryActivity__JumpCenter.builder(this).setNetToolType(9).setToolType(ToolCode.TOOL_BX).create().go();
    }
    @Recipient(tag = tag + CHOSE_SPR_FINSH)
    void onChoseObjFinsh(int code, String info, List<PeopleEntity> peopleEntityList, List<Integer> checkIds) {
        tvSpr.setText(checkIds.size() == 0 ? "" : info);
        sqrIds.clear();
        sqrIds.addAll(checkIds);
        peopleEntities.clear();
        peopleEntities.addAll(peopleEntityList);
    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW){
            showToast("最多添加"+CHOSE_PIC_MAX_SIZW+"张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }
            @Override
            public void chosePhoto() {
                AplyyRepairActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(AplyyRepairActivity.this);
            }
        });

    }
    @OnClick(R.id.layout_chose_spr)
    public void onLayoutChoseSprClicked() {
        if (peopleEntities.size() == 0) {
            HttpHeper.get().toolService().getCommonSpr(9)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<ArrayList<PeopleEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(ArrayList<PeopleEntity> data) {
                            peopleEntities.addAll(data);
                            ChosePeopleActivity__JumpCenter.builder(AplyyRepairActivity.this).setTag(tag).setData(peopleEntities).create().go();
                        }
                    });
        } else {
            ChosePeopleActivity__JumpCenter.builder(AplyyRepairActivity.this).setTag(tag).setData(peopleEntities).create().go();

        }    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath =   FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size() ,mSelected.size());
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AplyyRepairActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID+".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }

}
